package com.chenxbook.modules.examples.eventlistener;

import lombok.extern.slf4j.Slf4j;
import org.jbpm.api.listener.EventListener;
import org.jbpm.api.listener.EventListenerExecution;
import org.jbpm.pvm.internal.model.ActivityImpl;
import org.jbpm.pvm.internal.model.ExecutionImpl;
import org.jbpm.pvm.internal.model.TransitionImpl;

/**
 * 事件监听必须实现EventListener
 * <br> 取回场景的流程定义，动态创建一条用于取回的路径
 */
@Slf4j
public class WithdrawListener implements EventListener {

    private static final long serialVersionUID = 30044957906215717L;

    /**
     * 动态创建一条用于取回的路径
     */
    @Override
    public void notify(EventListenerExecution execution) throws Exception {
        TransitionImpl transition = ((ExecutionImpl) execution).getTransition();
        //获取取回发生点活动定义的对象
        ActivityImpl withdrawFrom = transition.getDestination();
        //获取取回目的地活动定义的对象
        ActivityImpl withdrawBackTo = transition.getSource();
        //取回合理性判断
        if(withdrawFrom==null ||withdrawBackTo==null ){
            String msg = "No support withdraw.";
            log.warn(msg);
            throw new Exception(msg);
        }
        //为取回动态创建一条转移路径
        TransitionImpl newTransition = withdrawFrom.createOutgoingTransition();
        newTransition.setName(withdrawFrom.getName() + " to " + withdrawBackTo.getName());
        newTransition.setDestination(withdrawBackTo);
    }
}
